package com.jhw.ymcc.mq;

import com.alibaba.fastjson.JSONObject;
import com.jhw.ymcc.constants.MqConstants;
import com.jhw.ymcc.domain.MessageSms;
import com.jhw.ymcc.dto.MessageSmsDto;
import com.jhw.ymcc.dto.UserSmsDto;
import com.jhw.ymcc.service.IMessageSmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author jhw
 * @create 2022/10/12
 */
@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "message-sms-group",
        topic = MqConstants.COURSE_SMS_TOPIC,
        selectorExpression = MqConstants.COURSE_SMS_TAG
)
public class MessageSmsConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt message) {
        // 获取消息体，如果为空就不消费信息
        byte[] body = message.getBody();
        if (body == null || body.length == 0){
            return;
        }
        // 转换信息体
        MessageSmsDto messageSmsDto = JSONObject.parseObject(new String(body, StandardCharsets.UTF_8), MessageSmsDto.class);
        // 保存消息到数据库
        saveMessageSms(messageSmsDto);
        // 调用短信发送信息（这里只做打印）
        log.info("发送短信成功，消息标题为：{}, 消息内容为：{}, 用户电话为：{}", messageSmsDto.getTitle(),
                messageSmsDto.getContent(), messageSmsDto.getUsers());

    }

    private void saveMessageSms(MessageSmsDto messageSmsDto) {
        // 获取数据
        String title = messageSmsDto.getTitle();
        String content = messageSmsDto.getContent();
        List<UserSmsDto> users = messageSmsDto.getUsers();
        // 初始化数据
        MessageSms messageSms = new MessageSms();
        messageSms.setContent(content);
        messageSms.setTitle(title);
        messageSms.setSendTime(new Date());
        // 遍历用户id并保存数据
        users.forEach(e->{
            messageSms.setUserId(e.getId());
            messageSmsService.insert(messageSms);
        });
    }
}
